<template>
    <div id="container">
        <my-header></my-header>
        <el-main id="main">
            <!-- 标题 -->
            <div id="title">
                个人中心
            </div>
            <!-- 分割线 -->
            <!-- <el-divider></el-divider> -->
              <el-tabs v-model="activeTab">
                <!-- 个人信息标签页 -->
                <el-tab-pane label="个人信息" name="info">
                    <el-form label-width="80px" :model="info" label-position="left" id="info_form">
                        <el-form-item label="用户名">
                            <el-input v-model="info.username" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="用户ID">
                            <el-input v-model="info.uid" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="用户类型">
                            <el-input v-model="info.type" disabled></el-input>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <!-- 重置密码标签页 -->
                <el-tab-pane label="重置密码" name="reset_password">
                    <el-form :model="reset_info" :rules="rules" ref="reset_info">
                        <el-form-item label="原密码" prop="old_password">
                            <el-input v-model="reset_info.old_password"></el-input>
                        </el-form-item>
                        <el-form-item label="新密码" prop="new_password">
                            <el-input v-model="reset_info.new_password"></el-input>
                        </el-form-item>
                        <el-form-item label="重复新密码" prop="repeat_new_password">
                            <el-input v-model="reset_info.repeat_new_password"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset_password('reset_info')">重置密码</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <!-- 我的资产标签页 -->
                <el-tab-pane label="我的资产" name="asset">
                      <el-table
                        :data="assetsList.filter(data => !searchAsset || data.name.toLowerCase().includes(searchAsset.toLowerCase()))"
                        style="width: 100%">
                        <el-table-column
                            label="资源ID"
                            prop="id">
                        </el-table-column>
                        <el-table-column
                            label="资源名称"
                            prop="name"
                            width="250px">
                        </el-table-column>
                        <el-table-column
                            label="资源类型"
                            prop="type">
                        </el-table-column>
                        <el-table-column
                            label="上传时间"
                            prop="time"
                            width="150px">
                        </el-table-column>
                        <el-table-column
                            label="评分"
                            prop="score">
                        </el-table-column>
                        <el-table-column
                            align="right"
                            width="300px">
                            <template slot="header" slot-scope="scope">
                                <el-input
                                v-model="searchAsset"
                                size="mini"
                                placeholder="输入关键字搜索"
                                id="search-asset-input"/>
                            </template>
                            <template slot-scope="scope">
                                <el-button
                                size="mini"
                                @click="handleViewDetail(scope.$index, scope.row)">查看详情</el-button>
                                <el-button
                                size="mini"
                                type="success"
                                @click="handleUpdate(scope.$index, scope.row)">版本更新</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 消息中心标签页 -->
                <el-tab-pane name="messsge">
                    <span slot="label"><el-badge :value='no_read' class='item' size="mini">消息中心</el-badge></span>
                    <el-table
                        :data="messageList.filter(data => !searchMessage || data.content.toLowerCase().includes(searchMessage.toLowerCase()))"
                        style="width: 100%"
                        :row-class-name="isReadClass"
                        >
                        <el-table-column
                            label="标题"
                            prop="title"
                            width="200px">
                        </el-table-column>
                        <el-table-column
                            label="内容"
                            prop="content"
                            width="400px">
                        </el-table-column>
                        <el-table-column
                            label="发送时间"
                            prop="time"
                            width="200px">
                        </el-table-column>
                        <el-table-column
                            align="right"
                            width="150px">
                            <template slot="header" slot-scope="scope">
                                <el-input
                                v-model="searchMessage"
                                size="mini"
                                placeholder="输入关键字搜索"
                                id="search-message-input"/>
                            </template>
                            <template slot-scope="scope">
                                <el-button
                                size="mini"
                                type="danger"
                                v-if="scope.row.isRead !== 'read'"
                                @click="handleRead(scope.$index, scope.row)">已读</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 申请认证标签页 -->
                <el-tab-pane label="认证申请" name="certification_application">
                    <el-form :model="certification_form" :rules="certification_form_rules" ref="certification_form">
                        <el-form-item label="真实姓名" prop="real_name">
                            <el-input v-model="certification_form.real_name"></el-input>
                        </el-form-item>
                        <el-form-item label="工作单位" prop="work">
                            <el-input v-model="certification_form.work"></el-input>
                        </el-form-item>
                        <el-form-item label="工作证件号码" prop="work_number">
                            <el-input v-model="certification_form.work_number"></el-input>
                        </el-form-item>
                        <el-form-item label="认证类型" prop="type">
                            <el-radio v-model="certification_radio" label="1">教师认证</el-radio>
                            <el-radio v-model="certification_radio" label="2">企业用户认证</el-radio>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitCertification">提交认证</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-main>
        <!-- 资源更新模态框 -->

        <el-dialog title="资产版本更新" :visible.sync="uploadFormVisible">
            <el-form :model="uploadForm" :rules="uploadRules" ref="uploadForm">
                <el-form-item label="版本号" :label-width="formLabelWidth" prop="version">
                    <el-input v-model="uploadForm.version" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="文件上传" :label-width="formLabelWidth">
                    <el-upload
                        class="upload-demo"
                        drag
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :file-list="fileList"
                        :auto-upload="false"
                        multiple
                        ref="upload"
                        >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">不限制文件类型，大小不超过500MB</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="更新日志" :label-width="formLabelWidth" prop="desc">
                    <el-input type="textarea" v-model="uploadForm.desc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary">确认并提交审核</el-button>
            </div>
        </el-dialog>
        <my-footer></my-footer>
    </div>
</template>

<script>
import MyFooter from '../../components/MyFooter.vue';
import MyHeader from '../../components/MyHeader.vue';
import axios from 'axios';
export default {
    name:'My',
    data:function(){
        return{
            activeTab: 'info',
            info:{},
            reset_info:{
                'old_password':'',
                'new_password':'',
                'repeat_new_password':''
            },
            // 重置密码表单验证
            rules:{
                old_password: [
                    { required: true, message: '请输入您的旧密码', trigger: 'blur' },
                    { min: 8, max: 30, message: '长度在 8 到 30 个字符', trigger: 'blur' }
                ],
                new_password: [
                    { required: true, message: '请输入您的新密码', trigger: 'blur' },
                    { min: 8, max: 30, message: '长度在 8 到 30 个字符', trigger: 'blur' }
                ],
                repeat_new_password :[
                    { required: true, message: '请重复输入您的新密码', trigger: 'blur' },
                    { min: 8, max: 30, message: '长度在 8 到 30 个字符', trigger: 'blur' }
                ],
            },
            // 认证 表单验证
            certification_form_rules:{
                real_name: [
                    { required: true, message: '请输入您在身份证上的真实姓名', trigger: 'blur' },
                    { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
                ],
                work: [
                    { required: true, message: '请输入您的工作单位，例如：西北大学信息学院', trigger: 'blur' },
                    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
                ],
                work_number :[
                    { required: true, message: '请重复输入您工作证号码', trigger: 'blur' },
                    { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
                ],
            },
            assetsList:[],
            searchAsset:'',
            searchMessage:'',
            messageList:[],
            // 未读消息数
            no_read:0,
            // 资源更新
            uploadForm: {
                version:'',
                desc:''
            },
            formLabelWidth: '120px',
            uploadFormVisible:false,
            uploadRules:{
                version:[
                    {required: true,message: '请输入版本号', trigger: 'blur'},
                    {
                        validator:function(rule, value, callback){
                            let reg = /^\d+(\.\d+)?$/;
                            if(!reg.test(value)){
                                callback('只能输入数字和小数点，只允许存在一层子版本号，例如：2.1');
                            }else{
                                callback();
                            }
                        }
                    }
                ],
                desc:[
                    { required: true, message: '请输入资产描述', trigger: 'blur' },
                    { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' }
                ]
            },
            // 文件上传
            fileList:[],
            certification_radio :'1',
            certification_form:{
                'real_name':'',
                'work':'',
                'work_number':''
            }
        }
    },
    created:function(){
        this.getPersonalInfo();
        this.getPersonalAsset();
        this.getMessage();
    },
    mounted:function(){
        this.no_read = this.messageList.filter(item => item.isRead.indexOf("no") !== -1).length;
    },
    computed:{
        
    },
    methods:{
        getPersonalInfo:async function(){
            this.info = [];
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
                const res = await axios.get('/api/my/personal_info?uid='+this.$store.state.login.uid,headerConfig);
                if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.info = res.data.res.data;
                }else{
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        reset_password:function(reset_info){
            this.$refs[reset_info].validate(async (valid) => {
                if (valid) {
                    // 验证密码
                    if(this.reset_info.old_password === this.reset_info.new_password){
                        this.$message.error('旧密码和新密码不能一致！');
                        return;
                    }
                    if(this.reset_info.new_password !== this.reset_info.repeat_new_password){
                        this.$message.error('两次输入的新密码不一样，请检查后重新输入！');
                        return;
                    }
                    // 发请求
                    let post_data = {
                        old_password:this.reset_info.old_password,
                        new_password:this.reset_info.new_password,
                        uid:this.$store.state.login.uid
                    }
                    //console.log(post_data);
                    const headerConfig = { headers:
                      { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
                    };
                    try{
                      const res = await axios.post('/api/my/reset_password',post_data,headerConfig);
                      if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                      if(res.data.res.ok === 1){
                            this.$notify({
                                title: '成功',
                                message: res.data.res.msg,
                                type: 'success'
                            });
                        }else{
                            this.$notify({
                                title: '提示',
                                message: res.data.res.msg,
                                type: 'error'
                            });
                        }
                    }catch(e){
                        console.log(e);
                        this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
                    }
                } else {
                    this.$message.error('抱歉出错了！请根据红色文字提示修改信息后再进行提交');
                    return false;
                }
            });
        },
        getPersonalAsset:async function(){
            this.assetsList = [];
            let post_data = {
                uid:this.$store.state.login.uid
            }
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
                const res = await axios.post('/api/my/personal_asset',post_data,headerConfig);
                if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.assetsList = res.data.res.data;
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        getMessage:async function(){
            this.messageList = [];
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
                const res = await axios.get('/api/my/message?uid='+this.$store.state.login.uid,headerConfig);
                if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.messageList = res.data.res.data;
                    this.no_read = res.data.res.no_read;
                }else{
                    console.log(res.data.res.msg);
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        handleViewDetail:function(index,row){
            this.$router.push({ path: 'detail',query:{'id':row.id} });
        },
        handleUpdate:function(index,row){
            this.uploadFormVisible = true;
            this.uploadForm.name = row.name;

        },
        handleRead:async function(index,row){
            let post_data = {
                message_id:row.id
            }
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
                const res = await axios.post('/api/my/read',post_data,headerConfig);
                if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.$notify({
                        title: '成功',
                        message: res.data.res.msg,
                        type: 'success'
                    });
                    row.isRead = 'read';
                    this.no_read --;
                }else{
                    console.log(res.data.res.msg);
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        isReadClass:function({row,rowIndex}){
            if(row.isRead === 'read'){
                return 'read';
            }
        },
        // 认证
        submitCertification:function() {
            this.$refs.certification_form.validate(async (valid) => {
                if (valid) {
                    // 发请求
                    let post_data = {
                        uid:this.$store.state.login.uid,
                        username:this.$store.state.login.username,
                        real_name:this.certification_form.real_name,
                        work:this.certification_form.work,
                        work_number:this.certification_form.work_number,
                        target_role:parseInt(this.certification_radio)
                    }
                    //console.log(post_data);
                    const headerConfig = { headers:
                      { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
                    };
                    try{
                      const res = await axios.post('/api/admin/commit_certification',post_data,headerConfig);
                      if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                      if(res.data.res.ok === 1){
                            this.$notify({
                                title: '成功',
                                message: res.data.res.msg,
                                type: 'success'
                            });
                        }else{
                            this.$notify({
                                title: '提示',
                                message: res.data.res.msg,
                                type: 'error'
                            });
                        }
                    }catch(e){
                        console.log(e);
                        this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
                    }
                } else {
                    this.$message.error('抱歉出错了！请根据红色文字提示修改信息后再进行提交');
                    return false;
                }
            })
        },
    },
    components:{
        MyHeader,
        MyFooter
    }
}
</script>

<style lang="scss" scoped>
#container{
    width: 100%;
    background-color: #eee;
    min-width: 950px;
    #main{
        width:70%;
        min-height: 500px;
        margin-left: 15%;
        margin-right: 15%;
        margin-top:30px;
        margin-bottom:30px;
        background-color: #fff;
        box-sizing: border-box;
        padding:50px;
        #title{
            font-size: 28px;
            font-weight: bold;
            position: relative;
        }
        /deep/ .el-divider{
            margin: 20px;
            margin-left: 0;
            margin-right: 0;
        }
        #info_form{
            margin-top:20px;
        }
    }
}
/deep/ .el-input__inner{
    width:30%;
}
/deep/ .el-tabs__nav-scroll{
    padding-top:20px;
    overflow: auto;
}
/deep/ #search-asset-input{
    width:100%;
}
/deep/ #search-message-input{
    width:100%;
}
/deep/ .el-dialog .el-input__inner{
    width:100%;
}
/deep/ .read {
    background: #f0f9eb;
    color: gray;
}
</style>